package io.renren.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class DingTalkService {

    @Value("${spring.dingtalk.webhook-url}")
    private String webhookUrl;

    @Value("${spring.dingtalk.secret}")
    private String secret;

    private final RestTemplate restTemplate = new RestTemplate();

    public void sendTextMessage(String content) {
        log.info("sendTextMessage" + content);
        Map<String, Object> message = new HashMap<>();
        message.put("msgtype", "text");
        Map<String, String> text = new HashMap<>();
        text.put("content", content);
        message.put("text", text);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(message, headers);
        restTemplate.postForObject(webhookUrl, request, String.class);
    }

    // 如果使用加签方式，需要对请求进行签名
    public void sendTextMessageWithSignature(String content) {
        try {
            long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;

            // 创建并初始化 Mac 对象
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(secretKeySpec);

            String sign = Base64.getEncoder().encodeToString(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));

            String signedUrl = webhookUrl + "&timestamp=" + timestamp + "&sign=" + sign;

            Map<String, Object> message = new HashMap<>();
            message.put("msgtype", "text");
            Map<String, String> text = new HashMap<>();
            text.put("content", content);
            message.put("text", text);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(message, headers);
            restTemplate.postForObject(signedUrl, request, String.class);
        } catch (Exception e) {
            // 处理异常，例如记录日志
            e.printStackTrace();
        }
    }

}
